package com.iqik.rabbit.controller;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutionException;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RequestMapping("/create/{o_id}")
    public String order(@PathVariable(name = "o_id") String id) throws ExecutionException, InterruptedException {
        CorrelationData correlationData = new CorrelationData();
        rabbitTemplate.convertAndSend("ex.order", "routing.key.order", "order:" + id, correlationData);
        CorrelationData.Confirm confirm = correlationData.getFuture().get();
        if (!confirm.isAck())
            return "下单失败";
        rabbitTemplate.convertAndSend("ex.ttl.order", "routing.key.ttl.order", id);
        return "下单成功";
    }

    @RequestMapping("/pay/{o_id}")
    public String pay(@PathVariable(name = "o_id") String id) {
        Message receive = rabbitTemplate.receive("queue.ttl.order");
        String message = new String(receive.getBody());
        System.out.println("支付： " + message);
        return "success";
    }
}
